/**
 * Sample React Native App
 * https://github.com/facebook/react-native
 * @flow
 */

import React, {Component} from 'react';
import {
    DeviceEventEmitter,
    Image,
    ListView,
    RefreshControl,
    ScrollView,
    StyleSheet,
    Text,
    TouchableHighlight,
    View
} from 'react-native';

import Navigation from "../../../custom/Navigation";
import StyleUtils from "../../../res/styles/StyleUtils";
import ViewUtils from "../../../utils/ViewUtils";
import IparNetwork, {SERVER_TYPE} from "../../../httpUtils/IparNetwork";
import CommonUtils from "../../../common/CommonUtils";
import I18n from "../../../res/language/i18n";
import ModalListUtils from "../../../utils/ModalListUtils";
import {DATE_DATA} from "../../../res/json/monthsJson";
import moment from 'moment';

let split_rank = [];
let personalSalesDatas = [];
let ds = new ListView.DataSource({rowHasChanged: (r1, r2) => r1 !== r2});

export default class BvPage extends Component {
    constructor(props) {
        super(props);
        split_rank = [];
        this.state = {
            dataSource: ds,
            showLoading: false,
            modalVisible: false,
            selectMount: '',
            userID: this.props.user_id
        };
        this.iparNetwork = new IparNetwork();
        this.commonUtils = new CommonUtils();
        this.isActivity = this.props.bvType === 'myActivity';

    }

    componentWillUnmount() {
        this.iparNetwork = null;
    }

    componentDidMount() {
        this.getRewardInfo();

        CommonUtils.getAcyncInfo('getPv')
            .then((result) => {
                this.swap_amount = JSON.parse(result).swap_amount;
                this.currency_code = JSON.parse(result).currency_code;
            })

    }

    /*获取个人用户奖励信息*/
    getRewardInfo(startTime, defBvType, endTime) {
        this.setState({
            showLoading: true,
        });
        let type = '';
        let time = '';

        let url = SERVER_TYPE.admin + 'getReward?';
        var date = new Date();
        let years = startTime ? startTime.substring(0,7) : moment(date.setMonth(date.getMonth() - 1)).format("YYYY-MM");
        let systemYear = endTime ? endTime : moment(date).format("YYYY-MM-DD");
            // time = startTime ? '&start_time=' + startTime + '&end_time=' + systemYear : '';
        let bvType = this.props.bvType;
        if (bvType !== 'pv') {
            if (this.isActivity) {
                url = SERVER_TYPE.adminIpar + 'newUserOrder?';
                let acTime = startTime ? startTime : systemYear.substring(0, 4);
                time = '&action_time=' + acTime + '&end_time=' + systemYear;
            } else {//奖金
                type = '&split_rank=' + bvType;
            }

            // else {
            //     let value = defBvType ? defBvType : bvType;
            //     type = '&split_type=' + value;
            // }
        }

        // https://admin.iparbio.com/api/v1/newUserOrder?action_time=2017-01-01&end_time=2018-09-15&user_id=c43d2e6f-2941-3e03-bab6-cea6d3eb54c2

        split_rank = [];
        this.iparNetwork.getRequest(url,
            'user_id=' +
            this.state.userID +
            type + time + '&years=' + years)
            .then((result) => {
                this.setState({showLoading: false});
                if (result.code === 200) {
                    if (this.props.bvType === 'pv') {
                        for (i = 0; i < result.data.length; i++) {
                            if (result.data[i].split_rank > 1 &&
                                result.data[i].split_rank < 5 ||
                                result.data[i].split_rank === 6 ||
                                result.data[i].split_rank === 7) {
                                split_rank.push(result.data[i]);
                            }
                        }
                        this.setState({dataSource: ds.cloneWithRows(split_rank)})
                    } else {
                        if (this.props.bvType === '1' && defBvType !== 0) {
                            personalSalesDatas = result.data;
                            this.getRewardInfo(startTime, 0, endTime);
                        } else {
                            this.setState({dataSource: ds.cloneWithRows(result.data)});
                        }
                    }


                } else {
                    DeviceEventEmitter.emit('toast', I18n.t('default.fail'))
                }

            }).catch((error) => {
            console.log(error);
            this.setState({showLoading: false});
            DeviceEventEmitter.emit('toast', I18n.t('default.fail'))
        })
    }


    render() {
        let props = this.props;

        let _title = props.title || I18n.t('default.MyPersonalSales');
        let _content = props.title ? (props.content || ' ') : I18n.t('default.myLocalBVNote');

        if (!props.title) {
            switch (props.bvType) {
                case 'myActivity':
                    _title = I18n.t('default.myActivity');
                    _content = I18n.t('default.bonusesTheGlobal');
                    break
            }
        }


        return (
            <View style={StyleUtils.flex}>
                <Navigation
                    onClickLeftBtn={() => {
                        this.props.navigator.pop();
                    }}
                    leftButtonIcon={require('../../../res/images/ic_back.png')}
                    titleImage={require('../../../res/images/ic_ipar_logo.png')}
                />
                <ScrollView
                    refreshControl={
                        <RefreshControl
                            refreshing={this.state.showLoading}
                            onRefresh={() => this.getRewardInfo()}
                        />
                    }
                >
                    <View style={[StyleUtils.flex, {padding: 16}]}>
                        {ViewUtils.getTitleView(_title, _content)}
                        <TouchableHighlight
                            activeOpacity={0.7}
                            underlayColor={'#ededed'}
                            onPress={() => this.setState({
                                modalVisible: true,
                            })}
                        >
                            <Text
                                style={styles.startTimeText}>{DATE_DATA.year + (this.state.selectMount && this.state.selectMount + '-01')}{this.state.selectMount ? ' ~ ' + DATE_DATA.year + '-' + this.state.selectMount + '-31' : ''}</Text>
                        </TouchableHighlight>
                        <View>
                            {/*//默认显示tabText*/}
                            {ViewUtils.getDefaultTab([I18n.t('default.date'), I18n.t('default.amount'), !this.isActivity ? I18n.t('default.type') : null, I18n.t('default.status')], '', '', {height: 50}, StyleUtils.defaultTabTv)}
                        </View>
                        <ListView
                            dataSource={this.state.dataSource}
                            renderRow={this.isActivity ? this.renderOrderRow.bind(this) : this.renderRow.bind(this)}
                        />
                    </View>
                </ScrollView>

                <ModalListUtils
                    title={DATE_DATA.year}
                    onPress={(index, text) => this.onModalItemClick(index, text)}
                    close={() => this.setState({
                        modalVisible: false,
                    })}
                    visible={this.state.modalVisible}
                    dataSource={ds.cloneWithRows(new CommonUtils().getMonthsData())}
                    dataParam={'name'}
                />
            </View>)


    }


    /***
     * modal item click
     * @param index
     * @param text
     */
    onModalItemClick(index, text) {

        let month = new CommonUtils().getMonthsData()[index].code;
        this.setState({
            modalVisible: false,
            selectMount: '-' + month,
        });

        //index == 0  是 全部的
        this.getRewardInfo(index === 0 ? null : DATE_DATA.year + '-' + month + '-01', null, DATE_DATA.year + '-' + month + '-31')

    }

    /*orderStatus*/
    orderStatus(status) {
        let or_status;
        switch (status) {
            case 0:
                or_status = I18n.t('o.estimated');
                break;
            case 1:
                or_status = I18n.t('default.moneyPaid');
                break;
            case 2:
                or_status = I18n.t('o.calculated');
                break;
            case 3:
                or_status = I18n.t('default.pending');
                break;
            case 4:
                or_status = I18n.t('o.notQualified');
                break;
        }
        return or_status;
    }

    /*business list RenderRow*/
    renderRow(rowData, sectionID, rowID) {

        return <View>
            {ViewUtils.getDefaultTab([rowData.update_time ? rowData.update_time.substring(0, 11) : ' ',
                (rowData.pv ? rowData.pv : 0).toFixed(2) + ' PV',
                rowData.split_type === 0 ? I18n.t('default.bonusPoints') : I18n.t('default.wallet'),
                this.orderStatus(rowData.status)])}
        </View>
    }

    /* order list RenderRow*/
    renderOrderRow(rowData, sectionID, rowID) {

        return <View>
            {ViewUtils.getDefaultTab([rowData.update_time ? rowData.update_time.substring(0, 11) : ' ',
                (rowData.goods_amount ? rowData.goods_amount : 0).toFixed(2) + ' PV',
                this.commonUtils.orderStatus(rowData.order_status, rowData.return_type)])}
        </View>
    }


}
const styles = StyleSheet.create({
    startTimeText: {
        borderWidth: 1,
        padding: 8,
        paddingRight: 26,
        paddingLeft: 26,
        borderColor: '#bcbcbc',
        textAlign: 'center',
        margin: 10,
    }
});
